<template>
  <div id="mining-account">
    <van-tabs v-model="active">
      <van-tab :title="$t('市价')"></van-tab>
    </van-tabs>
    <div style="position: relative" class="px-30 pb-104">
      <mining-exchange-input :title="$t('从')" :isMoney="true" v-model="form.volume" :actions="actions"
        @select="onSelect('symbol', $event)" @input="onInput" @max="onMax" :type="1" :coin="form.symbol" :tips="[]"
        :showMax="true" />
      <div v-if="show" class="font-28 textColor">{{ $t('可用数量') }}：<span class="textColor">{{ amountAvailable
      }}&nbsp;{{ form.symbol.toUpperCase() }}</span>
      </div>
      <div class="flex ex-bg justify-center my-42 items-center">
        <img src="@/assets/image/exchange/icon_3.png" alt="" class="w-25 h-25" @click="onSwitch" />
      </div>
      <mining-exchange-input :title="$t('至')" :value="form.volume ? (form.volume * form.rate).toFixed(5) : ''"
        :actions="actions" @select="onSelect('symbol_to', $event)" :disabled="true" :type="2" :coin1="form.symbol_to"
        :tips="[]" :showMax="false" />
      <div class="exchange-btn w-full flex justify-center mt-20">
        <p class="h-100 btnMain mx-auto flex justify-center items-center text-white w-768" @click="onConfirm">
          {{ $t('询价') }}
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import MiningExchangeInput from "@/components/mining-exchange-input";
import { Grid, GridItem, Popup, Icon } from "vant";
// import { mapState } from "vuex";
import { _exchangeRage, _getAllWallet, _getBalance, _initWidthdrawl, _widthdrawl, _records } from "@/API/fund.api";
import { _getBalance as __getBalance } from '@/API/trade.api'
import { mapGetters } from "vuex";
import Axios from "@/API/recharge";
import { List, PullRefresh, Tab, Tabs } from 'vant';
import { debounce } from '@/utils/utis'
export default {
  name: "MiningAcccount",
  components: {
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    MiningExchangeInput,
    [List.name]: List,
    [PullRefresh.name]: PullRefresh,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapGetters('user', ['userInfo']),
    amountAvailable() {
      let res
      let data = this.wallets.find(item => item.symbol === this.form.symbol.toLowerCase())
      if (data) {
        res = data.usable
      } else {
        res = 0
      }
      return res;
    },
    tabList() {
      return [
        { id: 1, text: this.$t('提幣') },
        { id: 2, text: this.$t('交易記錄') }
      ]
    },
    addr() {
      const account = this.userInfo.account
      return account && account.substr(0, 5) + '********' + account.substr(account.length - 5)
    }
  },
  data() {
    return {
      showPopup: false,
      activeRecord: 'exchange',
      valueTwo: 0,
      rate: 0,
      form: { // 闪兑
        symbol: 'ETH',
        symbol_to: 'USDT',
        volume: '',
        rate: 0
      },
      interval: null,
      actions: [],
      balance: 0, // 质押余额
      page: 1,
      loading: false, // 当loading为true时，转圈圈
      finished: false,  // 数据是否请求结束，结束会先显示'已经全部加载完毕'
      noData: false,// 如果没有数据，显示暂无数据
      wallets: [], // 钱包列表
      active: 0

    }
  },
  created() {
    _getAllWallet().then(data => {
      let coinHead = ['usdt','btc','eth']
      let actions2 = []
      data.extends.map(item => {
        actions2.push({ symbol: item.symbol, name: item.symbol.toUpperCase() })
      })
      this.wallets = data.extends
      this.actions = actions2.sort((a,b)=>{ //usdt btc eth 放在前面
        if(coinHead.includes(a.symbol)){
          return -1
        }else{
          return 1
        }
      })
      this.form.symbol = this.actions[2].name
      let toObj = this.actions.find(item => {
        return item.symbol.toLowerCase() == 'btc'
      })
      this.form.symbol_to = toObj.name
    })
  },
  methods: {
    onMax() { // 最大
      if (this.amountAvailable / 1) {
        this.form.volume = this.amountAvailable
        this.onInput()
      } else {
        this.$toast(this.$t('你没有可提数量'))
      }
    },
    onInput() { // 获取最新
      this.clearInterval()
      if (this.form.volume == '') {
        this.form.get_volume = ''
      } else {
        this.debounceFn()
      }
    },
    debounceFn: debounce(function () {
      if(+this.form.volume <=0){
        this.$toast(this.$t('交易价格不能小于等于0'))
        return
      }else{
        this.fetchRate(true)
      }
    }, 800),
    fetchRate(callback) { // interval
      _exchangeRage(this.form).then(data => {
        const { get_rate } = data
        this.form.rate = get_rate
        this.clearInterval()
        if (callback && typeof callback === 'function') {
          callback()
        }
      })
    },
    onSwitch() { // 交换
      const temp = this.form.symbol
      this.form.symbol = this.form.symbol_to
      this.form.symbol_to = temp
      this.form.volume = ''
      this.clearInterval()
    },
    onSelect(type, evt) { // 选择
      if (evt.type == 0) {
        this.form['symbol'] = evt.item.name
      } else {
        this.form['symbol_to'] = evt.item.name
      }
      if (this.form.symbol !== this.form.symbol_to) {
        this.form.volume = ''
      }
      this.clearInterval()
    },
    onConfirm() { // 闪兑
      this.clearInterval()
      if (this.form.volume == '') {
        this.$toast(this.$t('请输入数量'));
      } else {
        this.fetchRate(() => {
          this.$emit("exchange", this.form);
        })
      }
    },
    clearInterval() { // 清除定时器
      clearInterval(this.interval)
      this.interval = null
    }
  },
  beforeDestroy() {
    // console.log('beforeDestroy')
    this.clearInterval()
  }
};
</script>

<style lang="scss" scoped>
#mining-account {
  ::v-deep .van-tabs__nav {
    @include themify() {
      background-color: themed("main_background") !important;
    }
  }

  ::v-deep .van-tab {
    @include themify() {
      color: themed("text_color");
    }
  }

  ::v-deep .van-tab--active {
    @include themify() {
      background: themed("main_background") !important;
    }
  }
}



.ex-bg {
  width: 70px;
  height: 70px;

  @include themify() {
    background: 12px solid themed("cont_background");
  }

  border-radius: 50%;
  margin: 30px auto;
}

.exchange-btn {
  margin-top: 400px;

  .btnMain {
    background: linear-gradient(90deg, #2C64D4 0%, #38AEEA 100%);
    border-radius: 10px;
  }
}
</style>
